<template>
  <div class="menu-wrapper">
    <category-dialog ref="memberCategoryDialog" :request="'memberCategory'" @confirm="dialogConfirm" />
    <office-dialog ref="officeDialog" @confirm="officeConfirm" />
    <el-form ref="memberForm" :model="form" :rules="rules" label-width="100px">
      <div style="width: 100%;display: flex;align-items: flex-end;border-bottom: 1px #eee solid;margin-bottom: 20px">
        <span style="font-size: 18px;color:#409EFF;margin: 10px 0;">基本信息</span>
      </div>
      <div style="display: flex">
        <el-form-item label="账号" :prop="'mobile'" :rules="rules.mobile">
          <span class="account_with">{{form.mobile}}</span>
        </el-form-item>
        <el-form-item label="默认密码" >
          <span class="account_with">123456</span>
          <!--          <span class="account_with">{{form.code}}</span>-->
        </el-form-item>

      </div>
      <div style="display: flex">
        <el-form-item label="姓名" :prop="'name'" :rules="rules.name">
          <el-input v-model="form.name" placeholder="请输入姓名" style="width: 200px" />
        </el-form-item>
        <el-form-item label="所属门店" prop='shopId' >
          <el-select  value-key="id"
                      v-model="form.shopName"
                      style="width: 200px"
                      :filter-method="remoteShop"
                      filterable
                      placeholder="请选择"
                      @change="shopselect">
            <el-option
              v-for="item in shoplist"
              :key="item.id"
              :label="item.name"
              :value="item">
            </el-option>
          </el-select>
        </el-form-item>
      </div>
      <div style="display: flex">
        <el-form-item label="等级" prop="vip">
          <el-select v-model="form.vip" style="width: 200px" :value-key="id" placeholder="请选择类型">
            <el-option v-for="item in vips" :key="item.id" :label="item.name" :value="item.vip" />
          </el-select>
        </el-form-item>
        <el-form-item label="类型" prop="paymentPluginId">
          <el-select v-model="form.memberType" style="width: 200px" placeholder="请选择付款方式">
            <el-option v-for="item in memberForm" :key="item.value" :label="item.name" :value="item.value" />
          </el-select>
        </el-form-item>
      </div>
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="其他信息" name="otherInfo">
          <div style="display: flex;">
            <el-form-item label="会员有效期"  prop="vipExpired" >
              <div class="memberValidity">
                <el-date-picker
                  v-model="form.vipExpired"
                  type="date"
                  placeholder="选择日期"
                  format="yyyy 年 MM 月 dd 日"
                  value-format="yyyy-MM-dd"
                >
                </el-date-picker>
              </div>
            </el-form-item>
          </div>
          <div style="display: flex">
            <el-form-item label="备用电话" prop="phone" class="redItem">
              <el-input v-model="form.phone" style="width: 500px" />
            </el-form-item>
          </div>
          <div style="display: flex">
            <el-form-item label="备注" class="redItem">
              <el-input v-model="form.memo" style="width: 500px" />
            </el-form-item>
          </div>
          <div style="display: flex">
            <el-form-item :label="optionsType" prop="paymentPluginId">
              <el-select v-model="form.paymentPluginId" style="width: 200px" placeholder="请选择付款方式">
                <el-option
                  v-for="item in optionsForm"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="客户分类">
              <el-input v-model="form.memberCategoryName" style="width: 200px" suffix-icon="el-icon-arrow-down" @focus="dialogShow" />
            </el-form-item>
          </div>
          <div style="display: flex">

            <el-form-item label="经理">
              <el-select
                v-model="salesmanName"
                style="width: 200px"
                :filter-method="remoteSalesman"
                value-key="id"
                filterable
                placeholder="请选择"
                @change="selectSalesman"
                @focus="memberFocus"
              >
                <el-option v-for="item in salesmanList" :key="item.id" :label="item.name" :value="item" />
                <el-option key="-" style="background-color: #DCDFE6;text-align: center;" label="底部隐藏块" value="-" />
                <el-option key="/" style="background-color: #909399;color:white ;text-align: center;position: absolute;bottom:0;width: 100%" label="--- 搜索 ---" value="/" />
              </el-select>
            </el-form-item>
            <el-form-item label="推荐人名" prop="officeName">
              <el-select
                v-model="promoterName"
                style="width: 200px"
                :filter-method="remoteMethod"
                value-key="id"
                filterable
                placeholder="请选择"
                @change="changMember"
              >
                <el-option
                  v-for="item in memberList"
                  :key="item.id"
                  :label="item.name"
                  :value="item"
                />
              </el-select>
            </el-form-item>

          </div>

          <div style="display: flex">
            <el-form-item label="电子邮箱">
              <el-input v-model="form.email" style="width: 200px" />
            </el-form-item>
            <el-form-item label="纳税识别号" prop="taxNum">
              <el-input v-model="form.taxNum" style="width: 200px" />
            </el-form-item>

          </div>
          <!--      <el-form-item label="所在地址" prop="areaId" style="width: 600px">-->
          <!--        <Distpicker @selected="onSelected" :province="district.province" :city="district.city"-->
          <!--                    :area="district.area"></Distpicker>-->
          <!--      </el-form-item>-->
          <!--              <el-form-item label="详细地址" prop="address" style="width: 600px">-->
          <!--          <el-input v-model="form.address" />-->
          <!--      </el-form-item>-->
          <el-form-item>
            <el-button type="primary" :loading="clicked" @click="updateMember('memberForm')">
              完 成
            </el-button>
          </el-form-item>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <el-dialog
      v-el-drag-dialog
      title="双击选择经理"
      :visible.sync="salesmanType"
      width="950px"
      append-to-body
      :before-close="salesmanTableClose"
    >
      <div style="position: relative">
        <sysEmployeeTable @sysEmployeeDouble="sysEmployeeDouble"/>
      </div>
    </el-dialog>
  </div>
</template>
<style scoped lang="scss">
.menu-wrapper {
  margin: 15px;
}
.deleted_OrderHeader {
  padding-top: 5px;
  padding-bottom: 10px;
  margin: 10px 0;
  border-left: 1px solid #f2f2f2;
  border-bottom: 1px solid #f2f2f2;
}
.redItem >>> .el-form-item__label{
  color: red;
}
.memberValidity .el-date-editor{
  width: 200px!important;
}
.account_with{
  display: inline-block;
  width: 200px;
}
</style>
<script>

import { list as memberList } from '@/api/member'
import OfficeDialog from '@/components/OfficeDialog'
import loadMore from '@/utils/loadMore.js'
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import permission from '@/directive/permission/index.js' // 权限判断指令
import { list } from '../../api/vip'
import { EventBus } from '@/api/eventBus'
import utils from '../../utils/utils.js'
import Distpicker from '@/components/Distpicker/Distpicker'
import { update, find, deposit, point, receiver } from '@/api/member'
import { checkUserExists } from '@/api/sysUser'
import md5 from 'js-md5'
import CategoryDialog from '@/components/CategoryDialog'
import { list as companys } from '../../api/company'
import {list as shoplist,} from '@/api/shop'
import {list as sysEmployeeList} from '@/api/sysEmployee'
import sysEmployeeTable from '@/components/sysEmployeeTable/index'
export default {
  name: 'MemberEdit',
  filters: {},
  directives: { permission, loadMore ,elDragDialog},
  components: {
    Distpicker, CategoryDialog, OfficeDialog,sysEmployeeTable
  },
  data() {
    return {

      shoplist:[],//所属门店列表
      promoterName: '',
      officeName: '',
      memberList: [],
      salesmanList:[],//业务员
      salesmanName:'',
      salesmanType:false,
      isSalesmanName:'',
      managerId:'',
      id: '',
      activeName: 'otherInfo',
      payLoads: '',
      vips: [],
      companyList: [],
      clicked: false, // 按钮防双击
      district: {},
      receiverList: [],
      depositList: [],
      pointList: [],
      form: {
        vipExpired:'',
        shopId:"",
        shopName:null,//所属门店名s
        officeId: '',
        companyId: '',
        balance: 0,
        paymentPluginId:'',
        managerId:'',
        point: 0,
        taxNum:'',
        code:'',
        name: '',
        birth: '',
        mobile: '',
        phone: '',
        email: '',
        gender: '0',
        areaId: 440000,
        areaName: '广东省广州市海珠区',
        address: '',
        vip: '',
        memberCategoryId: '',
        memberType: '0',
        memo:null,
        memberCategoryName:""
      },
      vipName: '',
      dateName: '出生日期',
      optionsType: '付款方式',
      optionsForm: [
        { name: '现金', value: 'cashPayPlugin' },
        { name: '月结', value: 'debtPayPlugin'},
        { name: '代销', value: 'salePayPlugin'},
      ],
      memberForm: [
        { name: '个人客户', value: '0' },
        { name: '企业客户', value: '1'},
        { name: '批发客户', value: '2'},
      ],
      rules: {
        name: [
          { required: true, message: '请输入商户名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入联系电话', trigger: 'blur' }
        ],
        vip: [
          { required: true, message: '请选择等级', trigger: 'blur' }
        ],
        shopId: [
          { required: true, message: '请选择所属门店', trigger: 'blur' }
        ],
      },
      flowing: []
    }
  },
  watch: { // 路由地址不变的情况下,如果id变化则重新获取数据
    $route(newVal, oldVal) {
      console.log(newVal)
      if (newVal.name == 'member-edit' && newVal.query.id != this.id) {
        this.getData()
      }
    }
  },
  activated() {
    this.payLoads = new Date().getTime()
  },
  created() {
    this.loadCompany('')
    this.loadMember('')
    this.getData()
    this.shoplistshow()
    this.loadShopClick('')
    this.loadSalesman('')
  },
  methods: {
    shopselect(val){
      this.form.shopId=val.id
      this.form.shopName=val.name

    },
    shoplistshow(){
      shoplist().then(res=>{
        this.shoplist=res.data.data
      })
    },

    loadShopClick(query){
      var _this = this
      const params = new URLSearchParams()
      params.append('name', query)
      shoplist(params).then(response => {
        console.log(response)
        _this.shoplist = response.data.data
      }).catch(error => {
        console.log(error)
      })
    },
    remoteShop(query){
      this.loadShopClick(query)
    },
    changMember(data) {
      this.form.promoterId = data.id
      this.promoterName = data.name
    },
    // 会员选择
    loadMember(query) {
      var _this = this
      const params = new URLSearchParams()
      params.append('name', query)
      memberList(params).then(response => {
        console.log(response)
        _this.memberList = response.data.data
      }).catch(error => {
        console.log('error!!')
      })
    },
    officeConfirm(val) {
      this.form.officeId = val.id
      this.officeName = val.name
    },
    remoteMethod(query) {
      this.loadMember(query)
    },
    productMethod(query) {
      this.loadCompany(query)
    },
    officeShow() {
      console.log('点击了')
      this.$refs.officeDialog.show()
    },
    loadCompany(query) {
      companys({ name: query }).then(res => {
        this.companyList = res.data.data
      })
    },
    getData() {
      this.activeName = 'otherInfo'
      this.id = this.$route.query.id
      this.loadVip()
      var _this = this
      find(_this.id).then(response => {
        console.log(response)
        if (response.type == 'success') {
          _this.form.id = _this.$route.query.id
          _this.officeName = response.data.officeName
          _this.promoterName = response.data.promoterName
          _this.form.shopId=response.data.member.shopId

          // _this.form.vipExpired=response.data.member.vipExpired
          _this.form.vipExpired= utils.dateFormatter(response.data.member.vipExpired)

          // item.nearBuyDate = utils.dateFormatter(item.vipExpired)

          _this.form.shopName=response.data.member.shopName
          _this.form.taxNum=response.data.member.taxNum
          _this.form.promoterId = response.data.member.promoterId
          _this.form.paymentPluginId=response.data.member.paymentPluginId
          _this.form.officeId = response.data.member.officeId
          _this.form.point = response.data.point
          _this.form.code=response.data.member.code
          _this.form.companyId = response.data.member.companyId
          _this.form.balance = response.data.balance
          _this.form.name = response.data.member.name
          _this.form.birth = response.data.member.birth
          _this.form.mobile = response.data.member.mobile
          _this.form.phone = response.data.member.phone
          _this.form.email = response.data.member.email
          _this.form.gender = JSON.stringify(response.data.member.gender)
          _this.form.areaName = response.data.member.areaName
          _this.form.areaId = response.data.member.areaId
          _this.form.address = response.data.member.address
          _this.form.vip = response.data.member.vip
          _this.form.memo = response.data.member.memo
          _this.form.memberType = JSON.stringify(response.data.member.memberType)
          _this.district = {}
          const reg = /.+?(省|市|自治区|自治州|县|区)/g
          _this.district.province = _this.form.areaName.match(reg)[0]
          _this.district.city = _this.form.areaName.match(reg)[1]
          _this.district.area = _this.form.areaName.match(reg)[2]
          console.log(_this.form.areaName.match(reg))
          // _this.vipName = 'vip'+JSON.stringify(response.data.vip);
          _this.vipName = response.data.member.vip
          // _this.memberCategoryName = response.data.memberCategoryName;
          _this.form.memberCategoryName = response.data.member.memberCategoryName
          _this.form.memberCategoryId = response.data.member.memberCategoryId
          _this.form.managerId = response.data.member.managerId
          _this.salesmanName=response.data.managerName
          // _this.district = utils.decodeArea(response.data.areaId);


        } else {
          _this.$message({
            message: response.content,
            offset: 120,
            center: true
          })
        }
      }).catch(error => {
      })
    },
    handleClick(tab, event) {
      console.log(tab, event)
      if (tab.index == 1) {
        console.log('地址')
        receiver({ memberId: this.id }).then(res => {
          console.log(res)
          this.receiverList = res.data.data
        }).catch(err => {
          console.log(err)
        })
      } else if (tab.index == 2) {
        deposit({ memberId: this.id }).then(res => {
          console.log(res)
          this.depositList = res.data.data
        })
      } else if (tab.index == 3) {
        point({ memberId: this.id }).then(res => {
          console.log(res)
          this.pointList = res.data.data
        }).catch(err => {
          console.log(err)
        })
      }
    },
    loadVip() {
      list().then(res => {
        this.vips = res.data.data
      })
    },
    onSelected(val) {

      if (!utils.isNull(val.area) && !utils.isNull(val.area.code)) {
        this.form.areaId = val.area.code
        this.form.areaName = val.province.value+val.city.value+val.area.value
      }else if (!utils.isNull(val.city) && !utils.isNull(val.city.code)){
        this.form.areaId = val.city.code
        this.form.areaName = val.province.value+val.city.value

      }else if (!utils.isNull(val.province) && !utils.isNull(val.province.code)){
        this.form.areaId = val.province.code
        this.form.areaName = val.province.value
      }


    },
    dialogShow() {
      console.log('点击了')
      this.$refs.memberCategoryDialog.show()
    },
    dialogConfirm(val) {
      console.log(val)
      this.form.memberCategoryName = val.name
      this.form.memberCategoryId = val.id
    },
    updateMember(form) {
      const _this = this
      this.$refs[form].validate((valid) => {
        if (valid) { // 校验表单
          _this.clicked = true
          _this.form.birth = ''
          update(_this.form).then(response => {
            console.log(response)
            _this.clicked = false
            if (response.type == 'success') {
              this.$router.push({
                path: "/company/employeeList",
                query: { id: this.$route.query.companyId ,companyName: this.$route.query.companyName}
              });
            } else {
              _this.$message({
                message: response.content,
                offset: 120,
                center: true
              })
            }
          }).catch(error => {
            _this.clicked = false
          })
        } else {
          return false
        }
      })
    },
    memberTypeClick(val) {
      console.log(val)
      var _this = this
      if (val == 0) {
        _this.dateName = '出生日期'
        _this.optionsType = '性别'
        _this.optionsForm = [
          { name: '男', value: 0 },
          { name: '女', value: 1 },
          { name: '隐藏', value: 2 }
        ]
      } else {
        _this.dateName = '创建日期'
        _this.optionsType = '企业类型'
        _this.optionsForm = [
          { name: '企业', value: 1 },
          { name: '事业单位', value: 2 }
        ]
      }
    },
    goReceiver() {
      this.$router.push({
        path: '/receiver/list', query: { memberId: this.$route.query.id }
      })
    },
    // 经理
    loadSalesman(query){
      var _this = this
      const params = new URLSearchParams()
      params.append('name', query)
      sysEmployeeList(params).then(response => {
        console.log(response)
        _this.salesmanList = response.data.data
      }).catch(error => {
        console.log(error)
      })
    },
    remoteSalesman(query){
      this.loadSalesman(query)
    },
    selectSalesman(data){
      var _this = this
      if (data == '/') {
        _this.form.managerId = ''
        _this.salesmanType = true
      } else {
        _this.salesmanName=data.name
        _this.form.managerId = data.id
      }
    },
    memberFocus() {
      if (this.form.managerId != null || this.form.managerId != '') {
        this.isSalesmanName=this.salesmanName
        this.managerId = this.form.managerId
      }
    },
    // 经理弹窗
    salesmanTableClose() {
      this.form.managerId = this.managerId
      this.salesmanName=this.isSalesmanName
      this.salesmanType = false
    },
    sysEmployeeDouble(data) {
      this.form.managerId = data.id
      this.salesmanName=data.name
      this.salesmanType = false
    },
  }
}
</script>
